﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

/// <summary>
/// Summary description for Files
/// </summary>
public class TQBFiles
{
    /// <summary>
    /// 为上传的文件重新命名。
    /// </summary>
    /// <param name="oldFileName">例如：a1.jpg。</param>
    /// <returns></returns>
    public static string CreateFileName(string oldFileName)
    {
        Random random = new Random(unchecked((int)DateTime.Now.Ticks));

        string newFileName = (Environment.TickCount & int.MaxValue).ToString()
            + random.Next(1000, 9999).ToString()
            + Path.GetExtension(oldFileName).ToLower();

        return newFileName;
    }

    /// <summary>
    /// 判断是否存在文件。
    /// </summary>
    /// <param name="filePath">如：/upload/1/1.jpg。</param>
    /// <returns></returns>
    public static bool CheckFile(string filePath)
    {
        return System.IO.File.Exists(HttpContext.Current.Server.MapPath(filePath));
    }

    /// <summary>
    /// 检查是否存在文件夹目录。
    /// </summary>
    /// <param name="rootPath">要检查的目录。</param>
    /// <param name="isCreate">如果不存在，是否创建目录。</param>
    /// <param name="addDayDirectory">是否添加日期目录。</param>
    /// <returns>返回文件夹URL格式的路径：如：/upload/music/。</returns>
    public static string CheckFolder(string rootPath, bool isCreate, bool addDayDirectory)
    {
        if (string.IsNullOrEmpty(rootPath))
        {
            return "";
        }

        string physicalPath = "";

        if (!rootPath.EndsWith("/"))
            rootPath = rootPath + "/";

        if (addDayDirectory)
            rootPath += string.Format("{0}/{1}/{2}/", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

        physicalPath = HttpContext.Current.Server.MapPath(rootPath);

        if (!Directory.Exists(physicalPath))
        {
            if (isCreate)
                Directory.CreateDirectory(physicalPath);
            else
                return "";
        }

        return rootPath;
    }

    public static string UploadFile(HttpPostedFile hpf, string rootPath, bool isNewFileName)
    {
        string fileUrlPath = "";

        if (hpf != null && hpf.ContentLength > 0)
        {

            fileUrlPath = CheckFolder(rootPath, true, true);

            if (string.IsNullOrEmpty(fileUrlPath))
                return "";

            if (isNewFileName)
                fileUrlPath += CreateFileName(hpf.FileName);
            else
                fileUrlPath += hpf.FileName;

            try
            {
                hpf.SaveAs(HttpContext.Current.Server.MapPath(fileUrlPath));
            }
            catch
            {
                fileUrlPath = "Error";
            }
        }

        return fileUrlPath;
    }

}